package com.luke.dubbo.user.chain;

import com.luke.dubbo.user.chain.impl.AFilter;
import com.luke.dubbo.user.chain.impl.BFilter;
import com.luke.dubbo.user.chain.impl.CFilter;
import com.luke.dubbo.user.chain.impl.MyInvoker;
import java.util.ArrayList;
import java.util.List;

/**
 * 过滤器链测试类
 */
public class InvokerChainTest {

    public static void main(String[] args) throws Exception{
        Invoker invoker = new MyInvoker();
        Invoker invokerChain = buildInvokerChain(invoker); //返回Invoker（filter是AFilter）
        String result = invokerChain.invoke("Jack");
        System.out.println(result);
    }

    public static Invoker buildInvokerChain(final Invoker invoker){
        Invoker last = invoker;
        List<Filter> filters = new ArrayList<Filter>();
        filters.add(new AFilter());
        filters.add(new BFilter());
        filters.add(new CFilter());

        for (int i = filters.size() - 1; i >= 0; i--) {
            final Filter filter = filters.get(i);
            final Invoker next = last;
            last = new Invoker() {
                @Override
                public String invoke(String str) throws Exception {
                    return filter.invoke(next, str);
                }
            };
        }
        return last;
    }

}
